package com.woniuxy.service.impl;

import com.woniuxy.entity.Cart;
import com.woniuxy.mapper.CartMapper;
import com.woniuxy.service.CartService;
import com.woniuxy.utils.ResponseResults;
import com.woniuxy.utils.ResponseState;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;


@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Transactional
    @Override
    public ResponseResults<Boolean> addCart(Cart cart) {

        boolean cart1=false;

        // TODO 解决购物车反复添加的Bug
        if (cartMapper.selectCartByUidAndGid(cart.getUid(), cart.getGid()) != null) {
            // 不为空，说明订单已存在，需要增加数量num，更新
            cart1 = cartMapper.updateNumAndPrice(cart);
        } else {
            // 为空，说明订单不存在，创建新的订单记录，插入
            cart1 = cartMapper.insertCart(cart);
        }

        // 将cart插入数据库,并返回响应数据
        return new ResponseResults<Boolean>()
                .setCode(cart1 ? 200 : 500)
                .setState(cart1 ? ResponseState.ADD_SUCCESS : ResponseState.ADD_FAIL)
                .setMsg(cart1 ? "添加成功！" : "添加失败！")
                .setData(cart1);
    }

    @Override
    public ResponseResults<List<Cart>>  getAll(int uid) {

        List<Cart>  carts = cartMapper.findByUid(uid);

        return new ResponseResults<List<Cart>>()
                .setCode(200)
                .setState(ResponseState.SELECT_SUCCESS)
                .setData(carts);
    }

    // 增删改数据最好都添加事务
    @Transactional
    @Override
    public ResponseResults<Boolean> updateNum(Cart cart) {

        boolean b = cartMapper.updateNum(cart);
        return new ResponseResults<Boolean>()
                .setCode(b ? 200: 500)
                .setState(b ? ResponseState.UPDATE_SUCCESS:ResponseState.UPDATE_FAIL)
                .setMsg(b ? "修改成功！": "修改失败")
                .setData(b);
    }

    @Transactional
    @Override
    public ResponseResults<Boolean> del(int id) {

        boolean b = cartMapper.del(id);
        return new ResponseResults<Boolean>()
                .setCode(b ? 200: 500)
                .setState(b ? ResponseState.DEL_SUCCESS:ResponseState.DEL_FAIL)
                .setMsg(b ? "删除成功！": "删除失败")
                .setData(b);
    }

    @Override
    public List<Cart> findByIds(int[] ids) {
        return cartMapper.findByIds(ids);
    }

    @Override
    public int delCartByIds(int[] ids) {
        return cartMapper.delCartByIds(ids);
    }
}
